<template>
  <div class="vip-import">
    <div v-show="!isShowImportRecord">
      <!-- 头部 -->
      <div class="app-main-content-box">
        <app-main-title title="新增会员管理" />
        <div class="list-search clearfix">
          <div class="fl">
            <el-input
              v-model="filterForm[searchSelect]"
              placeholder="请输入内容"
              class="input-with-select"
              @keyup.enter.native="searchByKeyword"
            >
              <el-select slot="prepend" v-model="searchSelect" placeholder="请选择">
                <el-option
                  v-for="item in selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-input>
            <el-button
              :loading="searchLoading"
              type="primary"
              size="medium"
              round
              icon="el-icon-search"
              @click="searchByKeyword"
            >查 询</el-button>
          </div>

          <!-- 按钮组 -->
          <div class="fr" style="line-height:40px;">
            <el-dropdown
              split-button
              style="margin-right:10px"
              trigger="hover"
              type="primary"
              size="medium"
              @click="openDialogAddVip"
            >
              添加会员
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span style="display:block;" @click="openDialogUploadExcel">批量导入会员</span>
                </el-dropdown-item>
                <!-- <el-dropdown-item>
                <span style="display:block;" @click="downTemplate">下载模板</span>
                </el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
            <el-button size="medium" round @click="openBIndQrCode">获取二维码</el-button>
            <!-- <el-button size="medium" round @click="downTemplate">下载模板</el-button> -->
            <el-button size="medium" round @click="openImportRecord">导入任务</el-button>
          </div>
        </div>
      </div>

      <div class="app-main-content-box content">
        <!-- 筛选 -->
        <div class="app-main-filter-collapse-box">
          <el-collapse>
            <el-collapse-item title="按条件筛选" name="1">
              <div>
                <el-form ref="filterForm" :model="filterForm" label-width="120px" size="small">
                  <el-form-item label="导入日期：" prop="date">
                    <el-date-picker
                      v-model="filterForm.date"
                      type="datetimerange"
                      range-separator="~"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    />
                  </el-form-item>
                  <el-form-item label="卡类型：" prop="memberCategoryId">
                    <el-radio-group v-model="filterForm.categoryName" size="mini">
                      <el-radio label="all" border>全部</el-radio>
                      <el-radio
                        v-for="item in cardList"
                        :key="item.id"
                        :label="item.categoryName"
                        border
                      >{{ item.categoryName }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="绑定状态：" prop="binded">
                    <el-radio-group v-model="filterForm.binded" size="mini">
                      <el-radio label="all" border>全部</el-radio>
                      <el-radio label="false" border>未绑定</el-radio>
                      <el-radio label="true" border>已绑定</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" round @click="submitForm('filterForm')">筛 选</el-button>
                    <el-button round @click="resetForm('filterForm')">重 置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-collapse-item>
          </el-collapse>
          <div class="del-btn">
            <el-button :disabled="delIds.length===0" type="text" @click="del('checkIds')">删除已勾选</el-button>
            <el-button type="text" @click="del('all')">删除全部</el-button>
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="list-table">
          <el-table
            v-loading="tableLoading"
            :data="list"
            border
            stripe
            style="width: 100%"
            size="small"
            element-loading-text="加载中"
            empty-text="暂无数据"
            @selection-change="handleSelectionChange"
          >
            <el-table-column :selectable="checkboxInit" type="selection" width="55" fixed="left" />
            <el-table-column prop="name" label="姓名" fixed="left" />
            <el-table-column prop="binded" label="状态" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.binded?"已绑定":"未绑定" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="卡类型" />
            <el-table-column prop="entityCard" label="实体卡" />
            <el-table-column prop="sex" label="性别" width="50" />
            <el-table-column prop="phone" label="手机号" width="110" />
            <el-table-column prop="balance" label="实充余额(元)">
              <template slot-scope="scope">
                <span>{{ scope.row.balance|parseNumberToThousands(2,false) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="giftBalance" label="赠送余额(元)">
              <template slot-scope="scope">
                <span>{{ scope.row.giftBalance|parseNumberToThousands(2,false) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="points" label="会员积分(个)">
              <!--              <template slot-scope="scope">-->
              <!--                <span>{{ scope.row.points|parseNumberToThousands(2,false) }}</span>-->
              <!--              </template>-->
            </el-table-column>
            <el-table-column prop="registerShop" label="所属门店名称" />
            <el-table-column prop="promoterName" label="推广员" width="110" />
            <el-table-column prop="createTime" label="导入时间" width="160" />
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="openDetail(scope.$index, scope.row)">详情</el-button>
                <el-button
                  v-if="!scope.row.binded"
                  type="text"
                  size="small"
                  @click="del(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination-direction
            v-if="paginationConfig.total!==0"
            :config="paginationConfig"
            @sizeschange="sizesChange"
            @pagechange="pageChange"
          />
        </div>
      </div>
    </div>

    <!-- 录入会员 -->
    <dialog-add-vip ref="dialogAddVip" />

    <!-- 批量导入会员 -->
    <dialog-upload-excel ref="dialogUploadExcel" />

    <!-- 打开详情 -->
    <dialog-import-detail ref="dialogImportDetail" />

    <!-- 小程序绑定二维码 -->
    <dialog-bind-qr-code ref="bindQrCode" />

    <!-- 导入记录 -->
    <el-collapse-transition>
      <import-record v-show="isShowImportRecord" ref="importRecord" />
    </el-collapse-transition>
  </div>
</template>

<script>
// import { mapGetters } from "vuex";
import { mapActions } from 'vuex'
import {
  getAllVipCardList,
  getVipImportList,
  delVipImportNoBinded
} from '@/api/vip'
import DialogAddVip from './components/DialogAddVip'
import DialogUploadExcel from './components/DialogUploadExcel'
import DialogImportDetail from './components/DialogImportDetail'
import DialogBindQrCode from './components/DialogBindQrCode'
import ImportRecord from './components/ImportRecord'
export default {
  components: {
    DialogAddVip,
    DialogUploadExcel,
    DialogImportDetail,
    DialogBindQrCode,
    ImportRecord
  },
  data() {
    return {
      // 配置
      paginationConfig: {
        // 分页配置
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      selectOptions: [
        {
          value: 'name',
          label: '姓名'
        },
        {
          value: 'phone',
          label: '手机号'
        }
      ],
      // 状态
      isShowImportRecord: false, // 是否显示导入任务列表
      tableLoading: false, // 表格loading
      searchLoading: false, // 搜索loading
      downloadLoading: false, // 导出loading
      // 数据
      list: [], // 表格数据
      cardList: [], // 卡类型数据
      delIds: [], // 批量删除的id
      searchSelect: 'name', // 默认搜索的类型
      filterForm: {
        // 筛选数据
        name: '',
        phone: '',
        binded: 'all',
        categoryName: 'all',
        date: []
      },
      filterType: 'all' // 全部搜索还是单搜索
    }
  },
  watch: {
    searchSelect(val) {
      this.filterForm.phone = ''
      this.filterForm.name = ''
    }
  },
  // computed: {
  //   ...mapGetters(["fileBaseUrl"])
  // },
  mounted() {
    this.getVipCardList() // 获取卡列表
    this.initData() // 获取导入的记录
    this.getActiveMaIsOnline()
  },
  methods: {
    /**
       *  获取数据
       */
    // 获取小程序是否上线
    ...mapActions(['getAuthMa']),
    getActiveMaIsOnline() {
      this.getAuthMa()
    },

    /**
       *  获取数据
       */
    // 获取所有会员卡类型
    getVipCardList() {
      getAllVipCardList().then((res) => {
        this.cardList = res.data
      })
    },

    // 获取导入的数据
    initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 重置勾选
      this.delIds = []
      // 加入page
      this.filterForm.page = page
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      params.startTime = params.date ? params.date[0] : ''
      params.endTime = params.date ? params.date[1] : ''
      // 如果是key搜索
      if (this.filterType === 'key') {
        // 初始化数据
        delete params.binded
        delete params.categoryName
        delete params.startTime
        delete params.endTime
      }
      delete params.date
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }

      this.tableLoading = true
      getVipImportList(params)
        .then((res) => {
          this.tableLoading = false
          this.searchLoading = false
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .catch(() => {
          this.tableLoading = false
          this.searchLoading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    },

    // 初始化table多选按钮是否可以勾选
    checkboxInit(row, index) {
      if (row.binded) return 0
      // 不可勾选
      else return 1 // 可勾选
    },

    // 多选状态栏改变
    handleSelectionChange(rows) {
      if (rows) {
        const ids = []
        rows.map((item) => {
          ids.push(item.id)
        })
        this.delIds = ids
      }
    },

    /**
       * 按钮组
       */
    // 搜索
    searchByKeyword() {
      this.searchLoading = true
      this.filterType = 'key'
      this.initData(1)
    },

    // 单个录入
    openDialogAddVip() {
      this.$refs.dialogAddVip.open().then((res) => {
        this.initData()
      })
    },

    // 批量导入按钮
    openDialogUploadExcel() {
      this.$refs.dialogUploadExcel.open().then((res) => {
        this.initData()
      })
    },

    // 打开二维码
    openBIndQrCode() {
      if (!this.$store.state.wechat.maInfo.DEFAULT.isOnline) {
        this.$alert('商户小程序未正式发布，暂时不可以获取二维码！', '提示', {
          confirmButtonText: '确定',
          center: true,
          type: 'warning',
          callback: (action) => {}
        })
      } else {
        this.$refs.bindQrCode.open()
      }
    },

    // 下载模板
    // downTemplate() {
    //   var alink = document.createElement("a");
    //   alink.href =
    //     this.fileBaseUrl + "/business/template/member_import_template.xlsx";
    //   alink.download = "";
    //   alink.click();
    // },

    // 打开导入任务
    openImportRecord() {
      this.isShowImportRecord = true
      this.$emit('changeTabName', 'historyImport')
    },

    // 条件筛选
    submitForm() {
      this.filterType = 'all'
      this.initData(1)
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.filterForm = {
        // 筛选数据
        name: '',
        phone: '',
        binded: 'all',
        categoryName: 'all',
        date: []
      }
    },

    // 打开详情
    openDetail(index, row) {
      this.$refs.dialogImportDetail.open(row)
    },

    // 删除指定
    del(row) {
      const params = {}
      switch (row) {
        case 'checkIds':
          params.allDelete = false
          params.ids = this.delIds
          break
        case 'all':
          params.allDelete = true
          break
        default:
          params.allDelete = false
          params.ids = [row.id]
          break
      }
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          delVipImportNoBinded(params)
            .then((res) => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.initData()
            })
            .catch((err) => {})
        })
        .catch(() => {})
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .vip-import {
    /* 搜索*/
    .list-search {
      .el-select {
        width: 90px;
      }
      .el-input {
        width: 300px;
        margin-right: 10px;
      }
      .input-with-select .el-input-group__prepend {
        background-color: #fff;
      }
    }
    /* 内容区 */
    .content {
      margin-top: 10px;
      /* 删除按钮 */
      .del-btn {
        border-top: 1px solid #e7e7e7;
      }
      /* 表格 */
      .list-table {
        .table-avatar {
          overflow: hidden;
          width: 30px;
          height: 30px;
          border: 1px solid #f7f7f7;
          border-radius: 50%;
        }
      }
    }
  }
</style>
